import React, { Fragment } from "react"
import { Image, View } from "@tarojs/components"
import Taro from "@tarojs/taro"
import clsx from "clsx"
import { Like, LikeOutlined } from "@taroify/icons"
import { deleteNoteComment, switchCommentLike } from "@/apis/yikao-community"
import { requestIsFullfilled } from "@/utils/request"
import { useAppSelector } from "@/store/hook"
import styles from "./index.module.scss"
import { navigation } from "@/utils/router"
import { pageMapperCommunity } from "@/constants/pageMap"

type IProps = {
  className?: string
  comment: IApiRelative.IGetNoteComments.IGetNoteCommentItem
  /** 展开子级评论 */
  onExpandChildren: (parentId?: number) => void
  /** 点赞成功回调 */
  onLike: (
    commentId: number,
    meta: IApiRelative.ISwitchCommentLike.IResData,
    parentId?: number
  ) => void
  /** 回复
   * @param {number} commentId 回复的那条目标评论id
   * @param {number} parentId 回复的那条目标评论的父级id(一般如果当前评论的时一级评论, 为0, 否则为评论的目标评论所属的一级评论id)
   */
  onReply: (commentId: number, parentId?: number) => void
  /** 删除评论成功后回调 */
  onRemove: (commentId: number, parentId?: number) => void
  /** 举报评论成功回调 */
  onReport: (commentId: number, parentId?: number) => void
}
/**
 * @component 评论组件
 */
export default function GpComment(props: IProps) {
  const { comment, ...childProps } = props
  const { className, onExpandChildren, onLike, onReply, onRemove, onReport } = childProps
  const authInfo = useAppSelector(state => state.auth.userInfo)
  const ownParentId = comment.parentId === 0 ? comment.id : comment.parentId
  function renderChildComments() {
    if (comment.childrenCount === 0) return null
    return (
      <View className="box-border mt-32px">
        {comment.children &&
          comment.children.map(child => (
            <GpComment
              comment={child}
              key={child.id}
              {...childProps}
              className={styles.childComment}
            />
          ))}
        {comment.childNoteHasMore && (
          <View
            className="ml-60px text-28px"
            style={{ color: "#1B3C81" }}
            onClick={() => onExpandChildren(comment.id)}
          >
            展开更多回复
          </View>
        )}
      </View>
    )
  }
  /** 判断是否是自己的评论 */
  function isSeleComment() {
    return comment.miniVisitorId === authInfo.id
  }
  /**
   * 1、点击自己的评论时，出现删除和回复选项；
   * 2、点击他人的评论时，直接进入回复，长按则出现回复及举报操作
   */
  function handleClickCommentText() {
    if (isSeleComment()) {
      Taro.showActionSheet({
        itemList: ["回复", "删除"],
        success(result) {
          if (result.tapIndex === 0) {
            onReply(comment.id, ownParentId)
          } else if (result.tapIndex === 1) {
            deleteNoteComment({
              id: comment.id
            }).then(res => {
              if (requestIsFullfilled(res)) {
                Taro.showToast({
                  title: "删除成功",
                  icon: "none"
                })
                onRemove(comment.id, comment.parentId)
              }
            })
          }
        }
      })
    } else {
      onReply(comment.id, ownParentId)
    }
  }
  /** 长按他人的评论则出现回复及举报操作 */
  function handleLongPress() {
    if (isSeleComment()) return
    Taro.showActionSheet({
      itemList: ["回复", "举报"],
      success(result) {
        if (result.tapIndex === 0) {
          onReply(comment.id, ownParentId)
        } else if (result.tapIndex === 1) {
          onReport(comment.id, comment.parentId)
        }
      }
    })
  }
  /** 点赞 */
  function handleLike() {
    switchCommentLike({
      id: comment.id
    }).then(res => {
      if (requestIsFullfilled(res)) {
        Taro.showToast({
          title: comment.isSelfLike ? "已取消点赞" : "点赞成功",
          icon: "none"
        })
        const { likeCount, isLike } = res.data.data
        onLike(
          comment.id,
          {
            likeCount,
            isLike
          },
          comment.parentId
        )
      }
    })
  }
  /** 点击图片评论预览 */
  function handlePreviewImage(current: string) {
    Taro.previewImage({
      current,
      urls: comment.files.map(file => file.fileImage)
    })
  }
  /** 点击用户昵称头像等跳转对应个人主页 */
  function handleClickUser() {
    navigation(pageMapperCommunity.PersonalPage, { id: comment.miniVisitorId })
  }
  return (
    <View className={clsx(styles.comment, className)}>
      <View className="inline-flex flex-row items-center" onClick={handleClickUser}>
        <Image
          src={comment.miniVisitorHead || process.env.__DEF_AVATAR__}
          className="w-44px h-44px rounded-full object-cover block"
        />
        <View className="text-light text-26px font-normal ml-16px">{comment.miniVisitorName}</View>
        {comment.isAuthor && (
          <View
            style={{
              background: "#EEEEEE"
            }}
            className="text-light rounded-14px text-20px w-64px h-28px flex flex-row justify-center items-center box-border ml-8px"
          >
            作者
          </View>
        )}
      </View>
      <View className="ml-60px box-border">
        {/* 文字评论 */}
        {comment.content && (
          <View
            className="text-bold text-28px leading-36px box-border"
            onClick={handleClickCommentText}
            onLongPress={handleLongPress}
          >
            {comment.replyMiniVisitorName && (
              <Fragment>
                <View className="inline" onClick={() => onReply(comment.id, ownParentId)}>
                  回复
                </View>
                <View className="inline text-light pl-16px">{comment.replyMiniVisitorName}</View>：
              </Fragment>
            )}
            {comment.content}
          </View>
        )}
        {/* 图片评论 */}
        {comment.files && comment.files.length > 0 && (
          <View className="mt-16px">
            {comment.files.map(file => (
              <Image
                key={file.id}
                onClick={() => handlePreviewImage(file.fileImage)}
                src={file.fileImage}
                className="object-cover block w-200px h-200px box-border"
              />
            ))}
          </View>
        )}
        {/* 回复行 */}
        <View className="flex mt-16px flex-row items-center box-border">
          <View className="text-light text-24px">{comment.createdRelativeTime}</View>
          <View
            className="ml-16px text-bold text-24px"
            onClick={() => onReply(comment.id, ownParentId)}
          >
            回复
          </View>
          <View className="ml-auto text-light text-24px" onClick={handleLike}>
            {comment.isSelfLike ? (
              <Like size={12} color="#FA3F29" className="pr-8px" />
            ) : (
              <LikeOutlined size={12} color="#999999" className="pr-8px" />
            )}
            {comment.likeCount}
          </View>
        </View>
        {/* 子级评论 */}
        {renderChildComments()}
      </View>
    </View>
  )
}
